//
//  ZDNewFeatureViewController.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/10/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class ZDNewFeatureViewController: UICollectionViewController {
    
    var layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    let ZDItemCount = 4
    
    
    //MARK: - 重写构造方法 添加layout
    init() {
    
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

        
        self.collectionView!.registerClass(ZDNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        setupLayout()
    }
    
    //MARK: - 设置layout
    private func setupLayout() {
    
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        //设置水平滚动
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        //设置分页
        collectionView?.pagingEnabled = true
        //隐藏水平滚动条
        collectionView?.showsHorizontalScrollIndicator = false
        //取消弹簧效果
        collectionView?.bounces = false
    }
    
    //MARK: - 数据源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return ZDItemCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ZDNewFeatureCell
        
//        cell.backgroundColor = UIColor.randomColor()
        
        cell.featureImageViewIndex = indexPath.item
        
        return cell
    }
    
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        //取出当前可见cell的indexPath
        let indexPath = collectionView.indexPathsForVisibleItems().last
        
//        print(indexPath)
        
        //最后一页显示开始体验按钮
        if indexPath?.item == ZDItemCount-1 {
        
            let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! ZDNewFeatureCell
            
            cell.startButtonAnimation()
        }
    }
}




/// 自定义UICollectionViewCell
class ZDNewFeatureCell: UICollectionViewCell {
    
    
    //MARK: - 重写构造方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func prepareUI() {
    
        //添加到contentView中
        contentView.addSubview(featureImageView)
        contentView.addSubview(startButton)
        
        
        //使用第三方添加约束
        featureImageView.ff_Fill(contentView)
        
        startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
        
        
//        //添加约束
//        featureImageView.translatesAutoresizingMaskIntoConstraints = false
//        startButton.translatesAutoresizingMaskIntoConstraints = false
//        
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[fiv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["fiv" : featureImageView]))
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[fiv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["fiv" : featureImageView]))
//        
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
   
    }
    
    //MARK: - 开始按钮动画
    func startButtonAnimation() {
    
        //如果开始体验按钮是显示的 就不再执行动画
        if !startButton.hidden {
        
            return
        }
        
        startButton.hidden = false
        
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        UIView.animateWithDuration(0.5, delay: 0.1, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
                
        }
    }
    
    
    //MARK: - 开始按钮点击事件
    func startButtonClick() {
    
        (UIApplication.sharedApplication().delegate as! AppDelegate).switchController(ZDMainViewController())
    }
    
    
    var featureImageViewIndex: Int = 0 {
        
        didSet{
            
            //            print("new_feature_\(featureImageViewIndex)")
            
            featureImageView.image = UIImage(named: "new_feature_\(featureImageViewIndex + 1)")
            
            //隐藏按钮 在赋值的时候设置 可以避免cell重用带来的影响
            startButton.hidden = true
        }
    }
    
    private lazy var featureImageView: UIImageView = UIImageView()
    
    private lazy var startButton: UIButton = {
    
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setTitle("开始体验", forState: UIControlState.Normal)
        
        button.addTarget(self, action: "startButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    
}
